JavaScript Concurrency by Unknown

JavaScript Concurrency by Unknown

Author:Unknown
Language: eng
Format: mobi, epub, pdf
Publisher: Packt Publishing


Note

What happens when our code runs in the main thread just as often as it runs in a worker thread? Does this mean that we have to write our task code twice: once for sequential code and again for our workers? We obviously want to avoid this, so we need to keep our task code modular. It needs to be usable both in the main thread and worker threads.

Hardware concurrency capabilities

Another high-level check that we'll perform in our concurrent applications is the concurrency capabilities of the hardware that we're running on. This informs us how many web workers to create. For example, there's really nothing for us to gain by creating 32 web workers on a system where there are only four CPU cores. On this system, four web workers would be more appropriate. So, how do we get this number?

Let's create a generic function that figures this out for us:

// Returns the the ideal number of web workers // to create. function getConcurrency(defaultLevel = 4) { // If the "navigator.hardwareConcurrency" property // exists, we use that. Otherwise, we return the // "defaultLevel" value, which is a sane guess // at the actual hardware concurrency level. return Number.isInteger(navigator.hardwareConcurrency) ? navigator.hardwareConcurrency : defaultLevel; } console.log('concurrency level', getConcurrency()); // → concurrency level 8



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.